<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- 传输对象 再单独将索引值传过去 -->
        <ShopCar
          v-for="(item, index) in goodList"
          :key="index"
          :obj="item"
          :ind="index"
          @add="addFn"
          @aqq="aqqFn"
          @remove-event="removeFn"
          @change-checked="changeFn"
        ></ShopCar>
        <!-- 接收两个方法 -->
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{ total }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import ShopCar from "@/components/ShopCar.vue";

export default {
  computed: {
    total() {
      return this.goodList.reduce((sum, item) => {
        return (sum += item.price * item.num);
      }, 0);
      // console.log(a)
    },
    isAll: {
      get() {
        return this.goodList.every(obj => obj.checked === true);
      },
      set(value){
        this.goodList.forEach(item => item.checked = value)
      }
    },
  },

  components: {
    ShopCar,
  },
  methods: {
    // 接收子传过来的参数
    addFn(ind) {
      // 给遍历后的索引值所对应的num++
      this.goodList[ind].num++;
    },
    removeFn(obj) {
      const index = this.goodList.findIndex((item) => item === obj);
      this.goodList.splice(index, 1);
    },
    aqqFn(ind) {
      // 判断条件
      if (this.goodList[ind].num > 0) {
        this.goodList[ind].num--;
      } else {
        alert("减不动了");
      }
    },
    changeFn(ind) {
      this.goodList[ind].checked = !this.goodList[ind].checked
    }
  },
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: true,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    };
  },
};
</script>

<style></style>
